package com.wang.jmonkey.ca.handler.login.failure;

import com.alibaba.fastjson.JSONObject;
import com.wang.jmonkey.common.result.HttpResult;
import org.apache.http.HttpStatus;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 登陆失败操作
 * @Author HeJiawang
 * @Date 2021/5/11 17:40
 */
@Component
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(HttpStatus.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.addHeader("AccessControlAllowCredentials", "true");
        response.addHeader("AccessControlAllowOrigin", "*");

        HttpResult<Void> result = new HttpResult<>(HttpStatus.SC_FORBIDDEN, false, exception.getMessage());
        if (exception instanceof InternalAuthenticationServiceException) {  // todo
            result.setMsg("用户名或密码错误");
        }

        response.getWriter().write(JSONObject.toJSONString(result));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
